package com.group.controller;

import com.group.service.LoginService;
import com.group.service.UserService;
import com.group.service.impl.UserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pojo.entity.Record;
import pojo.entity.User;
import utils.BaseController;
import utils.BrowserUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Api(tags = "Shiro用户登录")
@Controller
public class UserController extends BaseController {

    @Autowired
    UserService userService;
    @Autowired
    private LoginService loginService;

    @ApiOperation("通过用户名查询用户")
    @RequestMapping("/findName")
    @ResponseBody
    public String findUserByName(String name){
        User user = userService.queryUserByName(name);
        return user.toString();
    }

    /**
     * 未登录时中转
     * @return
     */
    @RequestMapping("/toLogin")
    public void toLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/login.html").forward(request,response);
    }

    BrowserUtils browserUtils=new BrowserUtils();
    /**
     * 登录验证
     * @param userName
     * @param password
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public String login(String userName,String password,Integer type,HttpServletRequest request, HttpServletResponse response){
        //获取当前用户（获得一个用户）
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据（给用户《令牌》）
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        try {
            //验证令牌（login通过自定义的realm进行认证）
            subject.login(token);//执行登录的方法

            //获得登录成功后的user对象
            User user = userService.queryUserByName(userName);
            //写入session
            HttpSession session = request.getSession();
            session.setAttribute("user",user);
            if (user.getUserStatus()==type){
                String url = request.getHeader("USER-AGENT");
                String  browser = browserUtils.getBrowser(url);
                //日志存储
                String userJson = writerSuccessResult(user, response);
                Record record=new Record(user.getUserID(),0,0,1,browser);
                loginService.saveLog(record);
                return userJson;
            }else if (user.getUserStatus()==9){
                String successResult = writerSuccessResult(user);
                return successResult;
            }else {
                String error = writerErrorResult("身份不对！", response);
                return error;
            }
        }catch (UnknownAccountException e){
            return writerErrorResult("用户名错误！", response);
        }catch (IncorrectCredentialsException e){
            return writerErrorResult("密码错误！", response);
        }catch (DisabledAccountException  e){
            return writerErrorResult("账号被冻结！", response);
        }
    }

    /**
     * 权限不足
     * @return
     */
    @RequestMapping("/noauth")
    @ResponseBody
    public String unauthorized(){
        return "为将授权无法访问此页面";
    }

    /**
     * 退出登录
     * @return
     */
    @RequestMapping("/loginOut")
    public String loginOut(){
        Subject subject = SecurityUtils.getSubject();
        //退出登录
        if (subject.isAuthenticated()){
            subject.logout();
        }
        return "login.html";
    }
}
